import { Body, Controller, ForbiddenException, Get, Post, Query, UseGuards } from "@nestjs/common";
import { ApiBearerAuth, ApiCreatedResponse, ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";

import { JwtAuthGuard } from "../auth/guards/jwt-auth.guard";
import { CurrentUser } from "../common/decorators/current-user.decorator";
import { RequestUser } from "../common/interfaces/request-user.interface";
import { CreateOutputDto } from "./dto/create-output.dto";
import { ListOutputsDto } from "./dto/list-outputs.dto";
import { OutputListItemDto } from "./dto/output-list-item.dto";
import { OutputsListResponseDto } from "./dto/outputs-list-response.dto";
import { OutputsService } from "./outputs.service";

@Controller("outputs")
@UseGuards(JwtAuthGuard)
@ApiTags("Outputs")
@ApiBearerAuth()
export class OutputsController {
  constructor(private readonly outputsService: OutputsService) {}

  @Post()
  @ApiOperation({ summary: "提交产值上报" })
  @ApiCreatedResponse({ type: OutputListItemDto })
  async create(@CurrentUser() user: RequestUser, @Body() dto: CreateOutputDto) {
    this.ensureCanWrite(user);
    return this.outputsService.create(user.id, dto);
  }

  @Get()
  @ApiOperation({ summary: "分页查询产值上报记录" })
  @ApiOkResponse({ type: OutputsListResponseDto })
  findAll(@Query() query: ListOutputsDto) {
    return this.outputsService.findAll(query);
  }

  private ensureCanWrite(user: RequestUser) {
    const allowedRoles = ["ADMIN", "MANAGER"];
    const canWrite = user.roles.some((role) => allowedRoles.includes(role));

    if (!canWrite) {
      throw new ForbiddenException("Insufficient permissions to submit outputs");
    }
  }
}
